package MultiThread;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;

public class Spider {
	private Queue<URL> queue;
	private ArrayList<URL> links;
	private ArrayList<URL> mails;
	private int limit;
	
	public Spider(URL first, int limit){
		queue = new LinkedList<URL>();
		links = new ArrayList<URL>();
		mails = new ArrayList<URL>();
		queue.add(first);
		this.limit = limit;
	}
	
	public synchronized void isFinished(){
		while(links.size() + mails.size() < limit){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public synchronized boolean cont() {
		return links.size() + mails.size() < limit;
	}
	
	public synchronized void addLink(URL url){
		while(links.size() + mails.size() >= limit){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(isEmail(url)){
			if(!mails.contains(url)){
				mails.add(url);
			}
		}else{
			if(!links.contains(url)){
				links.add(url);
				queue.add(url);
			}
		}
		notifyAll();
	}
	
	public synchronized Collection<URL> getLinks(){
		return links;
	}
	
	public synchronized Collection<URL> getMails(){
		return mails;
	}
	
	public synchronized URL getURL(){
		while(queue.isEmpty()){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return queue.poll();
	}
	
	
	private boolean isEmail(URL url){
		if(url.toString().startsWith("mailto:")){
			return true;
		}
		return false;
	}

}
